package com.zscg.sequence.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.zgcs.sequence.net.in.InPackage;
import com.zgcs.sequence.tool.ServiceTool;
import com.zscg.sequence.disposer.DisposerManager;

public class SequenceService extends Service {

	Socket socket;
	InputStream input;
	OutputStream out;
	ByteArrayBuffer byteBuffer;
	String order;
	public static SequenceClinet clinet;

	/**
	 * 指令唯一标识，客户端传给服务端，服务端原数据返回
	 */
	public static int CMD_ID = 0;

	/**
	 * 默认接受数据量
	 */
	public static int DEFAULT_LENGTH = 128;
	/**
	 * "\"的BYTE值
	 */
	public static int BYTE_SLASH = 92;
	/**
	 * "n"的BYTE值
	 */
	public static int BYTE_N = 110;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

	}

	/**
	 * 初始化网络连接
	 */
	private void init() {
		
		new Thread() {

			public void run() {
				try {
					byteBuffer = new ByteArrayBuffer(512);
					socket = new Socket(ServiceTool.SERVICE_URL,
							ServiceTool.SERVICE_DSTPORT);
					input = socket.getInputStream();
					out = socket.getOutputStream();
					clinet = new SequenceClinet(SequenceService.this, out);
				} catch (UnknownHostException e1) {
					System.out.println("[service] init UnknownHostException");
				} catch (IOException e1) {
					System.out.println("[service] init IOException");
				}
//				clinet.login("chenhe@126.com", "000000");
				while (true) {
					byte[] temp = new byte[DEFAULT_LENGTH];
					int i;
					try {
						i = input.read(temp);
						if (i < DEFAULT_LENGTH) {

							byteBuffer.append(temp, 0, i - 2);
							order = new String(byteBuffer.toByteArray());
							System.out.println("[SequenceService] recive "
									+ order);
							disposeOrder(order);
							byteBuffer.clear();

						} else {
							if (i == DEFAULT_LENGTH
									&& temp[i - 2] == BYTE_SLASH
									&& temp[i - 1] == BYTE_N) {
								byteBuffer.append(temp, 0, i - 2);
								order = new String(byteBuffer.toByteArray());
								System.out.println("[SequenceService] recive "
										+ order);
								disposeOrder(order);
								byteBuffer.clear();
							} else {
								byteBuffer.append(temp, 0, temp.length);
							}
						}

						// if ((i = input.read(temp)) == DEFAULT_LENGTH
						// && (temp[DEFAULT_LENGTH - 2] != BYTE_SLASH
						// && temp[DEFAULT_LENGTH - 1] != BYTE_N)) {
						// byteBuffer.append(temp, 0, temp.length);
						// } else {
						//
						// byteBuffer.append(temp, 0, i);
						// order = new String(byteBuffer.toByteArray());
						// System.out.println("[SequenceService] recive "
						// + order);
						// disposeOrder(order);
						// byteBuffer.clear();
						// }
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

			};

		}.start();

//		this.clinet.login("chenhe@126.com", "000000");
	}

	/**
	 * 处理指令
	 * 
	 * @param order
	 */
	private void disposeOrder(String order) {
		System.out.println("[service order] " + order);
		String[] orders = order.split("\n");
		for (String morder : orders) {
			InPackage disposer = DisposerManager.DisposerOrder(morder);
			if (disposer != null)
				sendBroadcast(disposer.disposerOrder());
		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		init();
	}
}
